package com.llpy.controller;

import com.llpy.Service.MusicService;
import com.llpy.Service.SongService;
import com.llpy.dto.SongDto;
import com.llpy.mapper.SingerMapper;
import com.llpy.pojo.Singer;
import com.llpy.pojo.Song;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
public class SongController {
    private final SongService songService;

    @Autowired
    private MusicService musicService;


    @Autowired
    public SongController(SongService songService){
        this.songService = songService;
    }

    //添加歌曲
    @PostMapping("/saveSong")
    public Song saveSong(@RequestBody SongDto songDto){
        songDto.setName(songDto.getName().trim());
        songDto.setSingerName(songDto.getSingerName().trim());
        //歌手或名字为空
        if(songDto.getName().equals("")||songDto.getSingerName().equals("")){
            ObjectId id = new ObjectId(songDto.getMusicId());
            musicService.deleteMusic(id);
            return null;
        }else{
            //判断歌手是否存在
            Singer bySinger = songService.getBySinger(songDto.getSingerName());
            //不存在新建歌手
            if(bySinger==null){
                Singer singer = new Singer();
                singer.setName(songDto.getSingerName());
                songDto.setSinger(singer);
            }else{
                //否则将歌曲绑定这个歌手
                songDto.setSinger(bySinger);
            }
            return songService.saveSongAndSinger(songDto);
        }
    }

    //删除歌曲
    @PostMapping("/deleteSong")
    public boolean deleteSong(@RequestBody Map id){
        String id1 = (String) id.get("id");

        return songService.deleteSong(id1);
    }

    //查询歌手
    @GetMapping("/getSinger")
    public Singer getSinger(String name){
        return songService.getBySinger(name);
    }

    //查询歌曲
    @GetMapping("/getSong")
    public List<SongDto> getSong(String name){
        return songService.getBySong(name);
    }

    //查询所有歌曲
    @GetMapping("/getAllSong")
    public List<Song> getAllSong(){
        return songService.getAllSong();
    }
}
